﻿using Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Model;

namespace DAL
{
    public class PreparingNotationUpLoad
    {
        #region 构造函数
        public static string LocalImgDir = ConfigHelper.GetConfigString("LocalImgDir");
        public static string LocalResDir = ConfigHelper.GetConfigString("LocalResDir");
        public static long MaxResBlock = ConfigHelper.GetConfigInt("MaxResBlock") * 1024 * 1024;
        static object obj = new object();
        static object objRes = new object();
        string[] param;
        public PreparingNotationUpLoad() { }
        #endregion

        #region 上传批注
        /// <summary>
        /// 上传批注
        /// </summary>
        public void Up()
        {
            if (Monitor.TryEnter(obj))
            {
                Action<FileInfo[]> UpFile = (fileInfo) =>
                {
                    if (fileInfo == null || fileInfo.Length <= 0)
                        return;
                    foreach (var fi in fileInfo)
                    {
                        if (!fi.Name.IsPreparingNotationPic())
                            continue;
                        HttpRequestClient hrc = new HttpRequestClient();
                        //批注名称约定 备课编号_老师编号_课件编号_PPT页码索引.png
                        param = fi.Name.Substring(0, fi.Name.LastIndexOf('.')).Split('_');
                        hrc.SetFieldValue("FatherID", param[2]);
                        hrc.SetFieldValue("ReOrginName", fi.Name);
                        hrc.SetFieldValue("TechType", "1");
                        hrc.SetFieldValue("ReTypeCode", "RE0013");
                        hrc.SetFieldValue("UserID", param[1]);
                        hrc.SetFieldValue("SchoolID", ConfigHelper.GetConfigString("SchoolID"));
                        hrc.SetFieldValue("TimeStamp", Common.TimeStamp);
                        FileStream fs = new FileStream(fi.FullName, FileMode.OpenOrCreate);
                        byte[] buffer = new byte[fs.Length];
                        try
                        {
                            fs.Read(buffer, 0, buffer.Length);
                            fs.Seek(0, SeekOrigin.Begin);
                        }
                        finally
                        {
                            if (fs != null)
                                fs.Close();
                        }
                        hrc.SetFieldValue("file", fi.FullName, "application/octet-stream", buffer);
                        string responseText = string.Empty;
                        bool uploaded = hrc.Upload(ConfigHelper.GetConfigString("RemoteUrl") + "/Resources/File/PreparingNotationUpLoad", out responseText);
                        if (uploaded)
                        {
                            File.Delete(fi.FullName);
                        }
                        System.Threading.Thread.Sleep(1000);
                    }
                };
                var UpLoad = FunHelper.Fix<DirectoryInfo[], bool>(x => dirInfo =>
                {
                    if (dirInfo.Length > 0)
                    {
                        try
                        {
                            foreach (var di in dirInfo)
                            {
                                var _dir = new DirectoryInfo(di.FullName).GetDirectories();
                                if (_dir != null && _dir.Length > 0)
                                    x(_dir);
                                UpFile(di.GetFiles());
                                if ((DateTime.Now - di.CreationTime).TotalDays > 1)
                                {
                                    Directory.Delete(di.FullName);
                                }
                            }
                            return true;
                        }
                        finally
                        {
                            Monitor.Exit(obj);
                        }
                    }
                    return false;
                });

                var dirIfs = new DirectoryInfo(LocalImgDir).GetDirectories();
                var fileIfs = new DirectoryInfo(LocalImgDir).GetFiles();
                if (LocalImgDir.IsFileShareDir())
                {
                    using (IdentityScope iss = new IdentityScope(ConfigHelper.GetConfigString("FileShareSa"), ConfigHelper.GetConfigString("FileShareIp"), ConfigHelper.GetConfigString("FileSharePw")))
                    {
                        UpLoad(dirIfs);
                        UpFile(fileIfs);
                    }
                }
                else
                {
                    UpLoad(dirIfs);
                    UpFile(fileIfs);
                }
            }
        }
        #endregion

        #region 上传课堂资源
        public void UpRes()
        {
            if (Monitor.TryEnter(objRes))
            {
                #region UpFile--文件上传
                Action<FileInfo[]> UpFile = (fileInfo) =>
                {
                    if (fileInfo == null || fileInfo.Length <= 0)
                        return;
                    foreach (var fi in fileInfo)
                    {
                        if (!fi.Name.IsClassRes())
                            continue;

                        FileStream fs = new FileStream(fi.FullName, FileMode.OpenOrCreate);

                        long chunks = Convert.ToInt64(Math.Ceiling(fs.Length / (double)MaxResBlock));
                        string TimeStamp = Common.TimeStamp;
                        try
                        {
                            Func<long, long, FileStream, int> UpFunc = (_chunks, _length, _fs) =>
                            {
                                int code = 0;
                                for (int i = 0; i < _chunks; i++)
                                {
                                    #region 上传参数
                                    HttpRequestClient hrc = new HttpRequestClient();
                                    //资源名称约定 备课编号_老师编号_随机码.png
                                    param = fi.Name.Substring(0, fi.Name.LastIndexOf('.')).Split('_');
                                    //hrc.SetFieldValue("FatherID", param[2]);
                                    hrc.SetFieldValue("LessionID", param[1]);
                                    hrc.SetFieldValue("ReOrginName", fi.Name);
                                    hrc.SetFieldValue("TechType", "1");
                                    hrc.SetFieldValue("ReTypeCode", "RE0013");
                                    hrc.SetFieldValue("UserID", param[2]);
                                    hrc.SetFieldValue("SchoolID", ConfigHelper.GetConfigString("SchoolID"));
                                    hrc.SetFieldValue("TimeStamp", TimeStamp);
                                    hrc.SetFieldValue("chunks", chunks.ToString());
                                    hrc.SetFieldValue("size", _fs.Length.ToString());
                                    if (chunks > 1) hrc.SetFieldValue("chunk", i.ToString());
                                    #endregion

                                    byte[] buffer = new byte[chunks <= 1 ? _fs.Length : ((i + 1 < chunks) ? _length : _fs.Length % _length)];
                                    _fs.Read(buffer, 0, buffer.Length);

                                    hrc.SetFieldValue("file", fi.FullName, "application/octet-stream", buffer);
                                    string responseText = string.Empty;
                                    bool uploaded = hrc.Upload(ConfigHelper.GetConfigString("RemoteUrl") + "/Resources/File/ClassResUpLoad", out responseText);
                                    var result = JsonConvert.DeserializeObject<ResultRtn<dynamic>>(responseText);
                                    code = result.code;
                                }
                                return code;
                            };
                            if (UpFunc(chunks, MaxResBlock, fs) == 200)
                            {
                                fs.Close();
                                File.Delete(fi.FullName);
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.errorlog(ex);
                        }
                        finally
                        {
                            fs.Dispose();
                        }
                        System.Threading.Thread.Sleep(100);
                    }
                };
                #endregion

                #region UpLoad--递归目录
                var UpLoad = FunHelper.Fix<DirectoryInfo[], bool>(x => dirInfo =>
                {
                    if (dirInfo.Length > 0)
                    {
                        foreach (var di in dirInfo)
                        {
                            var _dir = new DirectoryInfo(di.FullName).GetDirectories();
                            if (_dir != null && _dir.Length > 0)
                                x(_dir);
                            UpFile(di.GetFiles());
                            if ((DateTime.Now - di.CreationTime).TotalDays > 1)
                            {
                                Directory.Delete(di.FullName);
                            }
                        }
                        return true;
                    }
                    return false;
                });
                #endregion

                

                var dirIfs = new DirectoryInfo(LocalResDir).GetDirectories();
                var fileIfs = new DirectoryInfo(LocalResDir).GetFiles();
                try
                {
                    if (LocalResDir.IsFileShareDir())
                    {
                        using (IdentityScope iss = new IdentityScope(ConfigHelper.GetConfigString("FileShareSa"), ConfigHelper.GetConfigString("FileShareIp"), ConfigHelper.GetConfigString("FileSharePw")))
                        {
                            UpLoad(dirIfs);
                            UpFile(fileIfs);
                        }
                    }
                    else
                    {
                        UpLoad(dirIfs);
                        UpFile(fileIfs);
                    }
                }
                catch (Exception ex)
                {
                    Log.errorlog(ex);
                }
                finally
                {
                    Monitor.Exit(objRes);
                }
            }
        }
        #endregion
    }
}
